package com.wjk.kylin.core.security;

import com.alibaba.fastjson.JSONObject;
import com.wjk.kylin.core.constant.CommonConstant;
import com.wjk.kylin.core.exception.BusinessException;
import com.wjk.kylin.modules.system.menu.service.IMenuService;
import com.wjk.kylin.modules.system.user.entity.User;
import com.wjk.kylin.modules.system.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * 首先我们需要自定义 UserDetailsService ，将用户信息和权限注入进来。
   我们需要重写 loadUserByUsername 方法，参数是用户输入的用户名。返回值是UserDetails，这是一个接口，一般使用它的子类org.springframework.security.core.userdetails.User，它有三个参数，分别是用户名、密码和权限集。
 * @author wangjkui
 * @date 2019/8/20
 */
@Slf4j
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private IUserService userService;
    @Autowired
    private IMenuService menuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByUserName(username);
        if (user == null) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }else if (CommonConstant.DataStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new BusinessException("对不起，您的账号：" + username + " 已停用");
        }

        //=========================权限==========================================
        Collection<SimpleGrantedAuthority> authorities = menuService.findMenuPermsByUser(user);
        if (authorities.isEmpty()) {
            log.info("登录用户：{} 无权限集合.", username);
            throw new BusinessException("对不起，您的账号：" + username + " 无权限");
        }

        log.info("登录用户：{}，权限集合：[{}]",username, JSONObject.toJSONString(authorities));

        // 返回UserDetails实现类
        return new AuthUser(user.getId(),user.getUserName(), user.getPassword(), authorities);
    }
}
